package gui.edit_objects;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.*;

import objects.Quartier;

import bdd_handler.QuartierDAO;
import bdd_handler.bdd;


public class Edit_Quartier extends JFrame implements ActionListener{

	private static final long serialVersionUID = 1L;

	private JFrame parent;

	private QuartierDAO qDAO;
	private Quartier q;
	private JTextField quartier_nom;
	private boolean mknew;
	private JButton valider, annuler;

	public Edit_Quartier(JFrame parent, Quartier quartier){
		//recuperation de la fenetre parente
		this.parent=parent;
		this.parent.setVisible(false);

		//construction de la fenetre
		this.q=quartier;
		if(q.getId_quartier()==-1)
			mknew=true;
		else
			mknew=false;
		if(mknew)
			this.setTitle("Nouveau Quartier");
		else
			this.setTitle("Editer Quartier");
		this.setSize(500,200);
		this.setResizable(false);
		JPanel pan=new JPanel();
		pan.setLayout(null);
		this.setContentPane(pan);

		//creation des DAOs
		bdd db=new bdd();
		qDAO=new QuartierDAO(db.getConnection());

		//creation objets internes
		quartier_nom=new JTextField(q.getNom());
		valider=new JButton("valider");
		valider.addActionListener(this);
		annuler=new JButton("annuler");
		annuler.addActionListener(this);
		JLabel lbl_quartier=new JLabel("Nom du quartier");

		//placer les objets
		pan.add(lbl_quartier);
		lbl_quartier.setBounds(10,10,200,20);
		pan.add(quartier_nom);
		quartier_nom.setBounds(220, 10, 200, 20);
		pan.add(annuler);
		annuler.setBounds(10, 40, 90, 20);
		pan.add(valider);
		valider.setBounds(110, 40, 90, 20);

		//action fermeture fenetre
		this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		this.addWindowListener(
				new WindowAdapter(){
					public void windowClosing(WindowEvent e){
						close();

					}
				}
				);
		//afficher la fenetre
		this.setVisible(true);
	}

	private void close(){
		this.parent.setVisible(true);
		this.dispose();
	}

	private void send()
	{
		q.setNom(quartier_nom.getText());
		if(mknew)
			qDAO.create(q);
		else
			qDAO.update(q);
	}

	private boolean check()
	{
		if(quartier_nom.getText().equals(""))
		{
			JOptionPane.showMessageDialog(this.getContentPane(), "le nom du quartier n'a pas été renseigné", "Oh zut!", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		return true;
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		Object source=e.getSource();

		if(source==annuler)
		{
			close();
		}
		if(source==valider)
		{
			if(check())
			{
				send();
				close();
			}
		}

	}

}
